# coding=utf-8
"""
作者：dnscmd@qq.com
创建时间：2025/4/9
描述：统计visio中的设备
"""
import re
from os.path import join

import vsdx


class VisioDeviceStat:
    number_pattern_str= r'\*\s*?\d+'
    number_pattern = re.compile(number_pattern_str)
    int_pattern = re.compile(r'\d+')

    def __init__(self, filename):
        self.filename = filename

    def get_page_txt_ls(self, page_idx=0):
        """
        获取特定页面中的文本信息
        :param page_idx: 获取page的页码（起始为0）
        """
        if not self.filename:
            return

        doc = vsdx.VisioFile(self.filename)
        page = doc.get_page(page_idx)

        elements = []
        for shape in page.child_shapes:
            text = shape.text.strip()
            if not text:
                continue
            elements.append(text.replace('\n', ''))

        return elements

    @classmethod
    def to_int(cls,s):
        if not s:
            return 0

        if isinstance(s,int):
            return s

        if isinstance(s,str):
            m = VisioDeviceStat.int_pattern.search(s)
            if not m:
                return 0
            return int(m.group())


    def split_device_num(self,page_idx=  0):
        """
        从文本中分离设备及其数量
        :param page_idx: 获取page的页码（起始为0）
        :return:
        """
        txt_ls = self.get_page_txt_ls(page_idx)
        if not txt_ls:
            return

        dic={}
        no_device_ls=[]
        for txt in txt_ls:
            matches = VisioDeviceStat.number_pattern.findall(txt)
            if not matches:
                no_device_ls.append(txt)
                continue

            device_ls = re.split(VisioDeviceStat.number_pattern_str,txt)
            for idx,n in enumerate(matches):
                num = VisioDeviceStat.to_int(n)
                dev = device_ls[idx].strip()
                if dev not in dic:
                    dic[dev]=num
                else:
                    dic[dev]+=num

        device_stata_ls=[(v[0],v[1]) for v in dic.items()]
        device_stata_ls.sort()
        return device_stata_ls,no_device_ls


if __name__ == '__main__':
    from vsdx import VisioFile

    root = r'C:\dns\works\09 普洱'
    filename = join(root, '普洱拓扑20250408.vsdx')  # 'my_file.vsdx'
    stat = VisioDeviceStat(filename)
    dev_ls,no_dev_ls = stat.split_device_num()
    for dev,num in dev_ls:
        print(dev,num)